package cdu.sl.controller;

import cdu.sl.common.PageResult;
import cdu.sl.common.Result;
import cdu.sl.dto.EmpQueryParamDTO;
import cdu.sl.entity.Employee;
import cdu.sl.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/emps")
@RequiredArgsConstructor
@Slf4j
public class EmployeeController {

    private final EmployeeService employeeService;

    /**
     * 查询所有员工
     */
    @GetMapping("/list")
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    public Result findAll() {
        log.info("查询所有员工");
        List<Employee> empList = employeeService.findAll();
        return Result.success(empList);
    }

    /**
     * 根据id删除员工
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result delete(@PathVariable Integer id) {
        log.info("根据id删除员工：{}",id);
        employeeService.delete(id);
        return Result.success();
    }

    /**
     * 根据id查询员工信息
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        log.info("根据id查询员工：{}",id);
        Employee emp = employeeService.findById(id);
        return Result.success(emp);
    }

    /**
     * 修改员工
     */
    @PreAuthorize("hasAuthority('USER_UPDATE')")
    @PutMapping()
    public Result update(@RequestBody Employee emp) {
        log.info("修改员工信息：{}",emp);
        employeeService.update(emp);
        return Result.success();
    }

    /**
     * 新增员工
     */
    @PreAuthorize("hasAuthority('USER_ADD')")
    @PostMapping()
    public Result add(@RequestBody Employee emp) {
        log.info("新增员工：{}",emp);
        employeeService.add(emp);
        return Result.success();
    }

    /**
     * 分页条件查询
     */
    @PreAuthorize("hasAnyRole('ADMIN','USER','MANAGER')")
    @GetMapping
    public Result page(EmpQueryParamDTO empQueryParam) {
        log.info("分页条件查询：{}",empQueryParam);
        PageResult<Employee> empList = employeeService.page(empQueryParam);
        return Result.success(empList);
    }


}
